const { logger } = require("../config/logConfig")
const utils = require('../config/utils')
const Article = require('../models/article')
const { validationResult } = require('express-validator')
const Category = require("../models/category")
const Tags = require("../models/Tags")
const sequelize = require("../config/database")
const { QueryTypes } = require("sequelize")


/**
 *  文章列表
 * @param {*} req 
 * @param {*} res 
 */
async function articleList (req, res) {
  let condition = utils.completeSelect(req.body)
  let pageObj = utils.pageSelect(req.body)
  try {
    const article = await Article.findAndCountAll({
      offset: pageObj.skip,
      limit: pageObj.limit,
      where: condition,
      order: [['ctime', 'DESC']], // 根据创建时间倒序排序
      distinct: true,
      attributes: {
        exclude: ["createdAt", "updatedAt"],
      },
      include: [
        {
          model: Category,
          as: 'category'
        }
      ]
    })
    if (!article) {
      utils.responseContent(res, 'OK', 200, data = { list: [], total: 0, pageSize: 10, pageNum: 1 })
    }
    let list = await Promise.all(article.rows.map(async item => {
      let tags = await Tags.findAll({
        where: {
          id: item.tags.split(',')
        },
        attributes: ['id', 'name'],
      });
      return {
        id: item.id,
        title: item.title,
        content: item.content,
        author_name: item.author_name,
        cover: item.cover,
        categoryId: item.categoryId,
        category_name: item.category.category_name,
        tags: tags,
        short_title: item.short_title,
        pinned: item.pinned,
        recommended: item.recommended,
        desc: item.desc,
        stats: item.stats,
        ctime: item.ctime,
        mtime: item.mtime
      }
    }))
    utils.responseContent(res, 'OK', 200, data = {
      list: list,
      pageNum: (pageObj.skip / pageObj.limit) + 1,
      pageSize: pageObj.limit,
      total: list.length
    })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ msg: '获取文章列表失败', code: 400 })
  }
}
/**
 * 文章新增
 * @param {*} req 
 * @param {*} res 
 */

async function articleAdd (req, res) {
  let { title, content, author_name, cover, categoryId, tags, short_title, pinned, recommended, desc, stats } = req.body
  try {
    logger.info(req)
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      for (var i = 0; i < errors.array().length; i++) {
        return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
      }
    }
    const count = await Article.count()
    let id
    if (count === 0) {
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(5, '0')
      id = `115${ randomNum }`
    } else {
      const maxIdArticle = await Article.findOne({ order: [['id', 'DESC']] })
      const maxId = parseInt(maxIdArticle.id) // 获取最大ID的数值部分
      id = maxId + 1
    }
    await Article.create({ id, title, content, author_name, cover, categoryId, tags: tags.join(','), short_title, pinned, recommended, desc, stats })
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.info(error)
    res.status(200).json({ msg: error, code: 500 })
  }
}

async function articleUpd (req, res) {
  let { id, title, content, author_name, cover, categoryId, tags, short_title, pinned, recommended, desc, stats } = req.body
  try {
    logger.info(req)
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      for (var i = 0; i < errors.array().length; i++) {
        return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
      }
    }
    // 查询数据
    const article = await sequelize.query(`SELECT id, title, content, author_name, cover, categoryId, tags, short_title, pinned, recommended, \`desc\`, stats, ctime, mtime, createdAt, updatedAt FROM Articles AS Article WHERE Article.id = ${id};`)
    if (article === null) {
      res.status(200).json({ msg: '查询文章失败', code: 0 })
    } else {
      let utime = new Date().getTime()
      await Article.update({ title, content, author_name, cover, categoryId, tags: tags.join(','), short_title, pinned, recommended, desc, stats, utime }, {
        where: {
          id,
        }
      })
    }
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.error(error)
  }
}
async function articleDetail (req, res) {
  const { id } = req.query
  try {
    logger.info(req)
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      for (var i = 0; i < errors.array().length; i++) {
        return res.status(400).json({ msg: errors.array()[i].msg, code: 0 });
      }
    }
    const [article] = await sequelize.query(`
    SELECT
    Article.id,
    Article.title,
    Article.content,
    Article.author_name,
    Article.cover,
    Article.categoryId,
    GROUP_CONCAT(CONCAT_WS('|', tag.id, tag.name) SEPARATOR ',') AS tags,
    Article.short_title,
    Article.pinned,
    Article.recommended,
    Article.desc,
    Article.stats,
    Article.ctime,
    Article.mtime,
    Article.createdAt,
    Article.updatedAt,
    category.id AS "category.id",
    category.category_name AS "category.category_name",
    category.rmk AS "category.rmk",
    category.seq AS "category.seq",
    category.stats AS "category.stats",
    category.ctime AS "category.ctime",
    category.mtime AS "category.mtime",
    category.createdAt AS "category.createdAt",
    category.updatedAt AS "category.updatedAt"
  FROM
    Articles AS Article
  LEFT OUTER JOIN 
    Categories AS category ON Article.categoryId = category.id
  LEFT OUTER JOIN
    Tags AS tag ON FIND_IN_SET(tag.id, Article.tags)
  WHERE
    Article.id = ${ id }
  GROUP BY
    Article.id;
  `, { type: QueryTypes.SELECT })
    if (article === null) {
      res.status(200).json({ msg: '查询文章详情失败', code: 0 })
    } else {
      let _tags = article.tags.split(',').map(item => {
        let temp = item.split('|')
        return {
          id: Number(temp[0]),
          name: temp[1]
        }
      })
      let response_data = {
        "id": article.id,
        "title": article.title,
        "author_name": article.author_name,
        "content": article.content,
        "cover": article.cover,
        "categoryId": article.categoryId,
        "short_title": article.short_title,
        "pinned": article.pinned,
        "recommended": article.recommended,
        "desc": article.desc,
        "stats": article.stats,
        "ctime": article.ctime,
        "mtime": article.mtime,
        "category.category_name": article['category.category_name'],
        "tags": _tags
      }
      res.status(200).json({ msg: 'OK', code: 0, data: response_data })
    }
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: error, code: 500 })
  }
}
module.exports = { articleAdd, articleList, articleDetail, articleUpd }
